#!/usr/bin/env python
#################################################################################
# Copyright 2018 ROBOTIS CO., LTD.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#################################################################################

# Authors: Gilbert #



#this program is designed for test.#
#just consider linear-motion#
import rospy
from geometry_msgs.msg import Twist, Point, Quaternion
import tf
from math import radians, copysign, sqrt, pow, pi, atan2,cos,sin
from tf.transformations import euler_from_quaternion
import numpy as np
from sensor_msgs.msg import LaserScan

msg = """
control your Turtlebot3!
-----------------------
this is follower1
-----------------------
"""
tb_leader_pos=Point()
tb_follower1_pos=Point()
tb_follower2_pos=Point()
tb_leader_vel=Twist()
tb_follower1_vel=Twist()

K0=0
K1=1.5
K2=0.1
K3=0
detect_R=1
safe_r=0.3
ID=1
dx=-0.5
dy=0.5


class GotoPoint():
    def __init__(self):
        rospy.init_node('pi_right', anonymous=False)
        #turtlebot3_model = rospy.get_param("model")

        rospy.on_shutdown(self.shutdown)
        self.cmd_vel = rospy.Publisher('cmd_vel', Twist, queue_size=10)
        self.tb_follower1_positon=rospy.Publisher('/tb_follower1_pos',Point,queue_size=10)
        position = Point()                          
        move_cmd = Twist()
        global r
        r = rospy.Rate(10)
        self.tf_listener = tf.TransformListener()
        self.odom_frame = 'odom'
        try:
            self.tf_listener.waitForTransform(self.odom_frame, 'base_footprint', rospy.Time(), rospy.Duration(1.0))
            self.base_frame = 'base_footprint'
        except (tf.Exception, tf.ConnectivityException, tf.LookupException):
            try:
                self.tf_listener.waitForTransform(self.odom_frame, 'base_link', rospy.Time(), rospy.Duration(1.0))
                self.base_frame = 'base_link'
            except (tf.Exception, tf.ConnectivityException, tf.LookupException):
                rospy.loginfo("Cannot find transform between odom and base_link or base_footprint")
                rospy.signal_shutdown("tf Exception")
        # print 66
        (position, rotation) = self.get_odom()
        rospy.Subscriber('/tb_leader_pos',Point,point_callback_1)
        # rospy.Subscriber('/tb_follower1_pos',Point,point_callback_2)
        rospy.Subscriber('/tb_follower2_pos',Point,point_callback_3)
        rospy.Subscriber('/tb_leader_vel',Twist,vel_callback_4)
        self.tb_follower1_positon.publish(position)
        # print 67
        global tb_leader_vel
        global tb_follower1_pos
        global tb_follower2_pos 
        global tb_follower1_vel

        delta_x=(tb_leader_pos.x-position.x+dx)
        delta_y=(tb_leader_pos.y-position.y+dy)
        # print ('deltax of Node 1 between leader is %f'%(delta_x))        
        # if abs(delta_x)<0.05:
        #     delta_x=0
        # if abs(delta_y)<0.05:
        #     delta_y=0
        goal_x=delta_x+position.x
        goal_y=delta_y+position.y
        goal_z=atan2(delta_y,delta_x)
        # print tb3_0_vel_delta_x;print tb3_0_vel_delta_y
        if delta_x==0 and delta_y==0:
            goal_z=0

        angular_now=rotation
        phi=goal_z
        avoid_delta=0

        tb_follower1_pos=position
        # print 68
        # obstacle_pos=self.lidar(position)
        # rospy.loginfo('position.x of the obstacle : %f', obstacle_pos.x)
        # rospy.loginfo('position.y of the obstacle : %f', obstacle_pos.y)
        pos_nodes=[tb_leader_pos,tb_follower1_pos,tb_follower2_pos]
        # print 77
        # pos_nodes=[tb3_0_pos,obstacle_pos]
        temp_x_sum=0
        temp_y_sum=0
        # for i in range(len(pos_nodes)):
        #     # print i
        #     if i!=ID:
        #         # print i
        #         # print pos_nodes[i].x
        #         r=sqrt(pow(pos_nodes[i].x-pos_nodes[ID].x,2)+pow(pos_nodes[i].y-pos_nodes[ID].y,2))
        #         print ('Distance of Node 1 to Node %d to Node is %f'%(i,r))
        #         if r>safe_r and r<detect_R:
        #             # temp_x=(pow(detect_R,2)-pow(safe_r,2))*(pos_nodes[i].x-pos_nodes[ID].x)
        #             # temp_y=(pow(detect_R,2)-pow(safe_r,2))*(pos_nodes[i].y-pos_nodes[ID].y)
        #             # temp_d2=pow(pos_nodes[i].x-pos_nodes[ID].x,2)+pow(pos_nodes[i].y-pos_nodes[ID].y,2)
        #             # temp_fenmu=temp_d2-pow(safe_r,2)
        #             # temp_fenmu=pow(temp_fenmu,3)
        #             # temp_x=temp_x/temp_fenmu*(temp_d2-pow(detect_R,2))
        #             # temp_y=temp_y/temp_fenmu*(temp_d2-pow(detect_R,2))
        #             # temp_x_sum=temp_x_sum+temp_x
        #             # temp_y_sum=temp_y_sum+temp_y
        #             temp_x=(1/r-1/detect_R)*(pos_nodes[ID].x-pos_nodes[i].x)
        #             temp_y=(1/r-1/detect_R)*(pos_nodes[ID].y-pos_nodes[i].y)
        #             temp_fenmu=pow(r,3)
        #             temp_x=temp_x/temp_fenmu
        #             temp_y=temp_y/temp_fenmu
        #             temp_x_sum=temp_x_sum+temp_x
        #             temp_y_sum=temp_y_sum+temp_y
        # # print 222

        avoid_delta=temp_x_sum*cos(angular_now)+temp_y_sum*sin(angular_now)  

        #############################################################################################
        # tb_follower1_vel.linear.x=K1*(delta_x*cos(angular_now)+delta_y*sin(angular_now))+K0*tb_leader_vel.linear.x+K3*avoid_delta
        delta_theta=self.compute_theta(phi,angular_now)
        #############################################################################################

        tb_follower1_vel.linear.x=0.1*(tb_leader_pos.x-position.x)+tb_leader_vel.linear.x
        #just consider linear-motion
        tb_follower1_vel.angular.z=K2*delta_theta
        print ('follower receive x of leader:%f y:%f'%(tb_leader_pos.x,tb_leader_pos.y))
        print ('follower receive vel_x of leader:%f'%(tb_leader_vel.linear.x))
        print ('follower receive x of follower:%f'%(position.x))
        print ('follower control vel:%f'%(tb_follower1_vel.linear.x) )
        self.cmd_vel.publish(tb_follower1_vel) 
    
    def lidar(self,tb_pos):
        msg = rospy.wait_for_message("scan", LaserScan)
        LIDAR_ERR = 0.05
        LIDAR_MAX = 1.5
        obstacle=[]
        min_dis=10
        min_ang=0
        min_point=Point()
        print 69
        for i in range(360):
            if i <= 45 or i > 315:
                obstacle_pos=Point()
                if msg.ranges[i] >= LIDAR_ERR and msg.ranges[i]<=LIDAR_MAX:
                    obstacle_pos.x=tb_pos.x+msg.ranges[i]*cos(i)
                    obstacle_pos.y=tb_pos.y+msg.ranges[i]*sin(i)
                    obstacle.append(obstacle_pos)
                    if msg.ranges[i] < min_dis:
                            min_dis = msg.ranges[i]
                            min_ang = i
        if min_dis<10:
            min_point.x=tb_pos.x+min_dis*cos(i)
            min_point.y=tb_pos.y+min_dis*sin(i)
        else:
            min_point.x=10
        return min_point


    def compute_theta(self,theta,rotation1):

        if theta*rotation1<0:
            if theta>0:
                if abs(rotation1)+theta<=pi:
                    w=abs(rotation1)+theta
                else:
                    w=-(2*pi+rotation1-theta)
            else:
                if rotation1+abs(theta)<=pi:
                    w=-(abs(theta)+rotation1)
                else:
                    w=(2*pi-rotation1+theta)
            print w
        else:

            w=theta-rotation1
            print w
        return w
        


    def get_odom(self):
        try:
            (trans, rot) = self.tf_listener.lookupTransform(self.odom_frame, self.base_frame, rospy.Time(0))
            rotation = euler_from_quaternion(rot)

        except (tf.Exception, tf.ConnectivityException, tf.LookupException):
            rospy.loginfo("TF Exception")
            return

        return (Point(*trans), rotation[2])
    def shutdown(self):
        self.cmd_vel.publish(Twist())
        r.sleep()
   
        
# def compute_theta(theta,rotation):
#         if theta*rotation1<0:
#             if theta>0:
#                 if abs(rotation1)+theta<=pi:
#                     w=abs(rotation1)+theta
#                 else:
#                     w=-(2*pi+rotation1-theta)
#             else:
#                 if rotation1+abs(theta)<=pi:
#                     w=-(abs(theta)+rotation1)
#                 else:
#                     w=(2*pi-rotation1+theta)
#         else:
#             w=theta-rotation1
#         return w
        
def point_callback_1(data):
    global tb_leader_pos
    tb_leader_pos.x=data.x
    tb_leader_pos.y=data.y
def point_callback_2(data):
    global tb_follower1_pos
    tb_follower1_pos.x=data.x
    tb_follower1_pos.y=data.y
def point_callback_3(data):
    global tb_follower2_pos
    tb_follower2_pos.x=data.x
    tb_follower2_pos.y=data.y
def vel_callback_4(data):
    global tb_leader_vel
    tb_leader_vel=data





if __name__ == '__main__':
    try:
        while not rospy.is_shutdown():
            print(msg)
            GotoPoint()
            r.sleep()

    except:
        rospy.loginfo("shutdown program.")

